-- | Reporting for Hexena.
-- All modules should return this data as we can have a unified
-- reporting.

-- Reporting is done as following, in the LaTeX file global
-- replacements should be added as lines beginnig with "%-- hexena:
-- <key>". These keys can be given as global replacements and they
-- will be replaced in the global template if the key is found, see
-- global Replacements which is a list of "[(key, value)]".
--
-- The template content will be written to a file "reportName.tex". In
-- this file all local replacements should have been done. A helper
-- function in this module will help you.

module Hexena.Reporting ( Report(..)
                        , replace
                        ) where

import Data.List
import qualified Data.Map as Map
import Data.Maybe
-- import qualified Data.String.Utils as S

data Report = Report {
      globalReplacements :: [(String, String)], -- later: Map.Map String String,
      templateContent :: String,
      reportName :: String,
      additionalFiles :: [(String, FilePath)]
    } deriving Show


-- | replace a String with a given list of key, value pairs. For each
-- | key the first occurrence of the string "@key@" is replaced
-- | by "value".
replace :: [(String, String)] -> String -> String
replace r s = let (pre, suf) = break ('@' ==) s
                  suf' = filter (isJust . snd) $ zip r $ map (flip stripPrefix (tail suf) . fst) r
                  suf'' = head suf'
              in if null suf then pre else pre ++ (if null suf' then "@" ++ replace r (tail suf) else (snd $ fst suf'') ++ (replace r $ tail $ fromJust $ snd suf''))
-- flip (foldl f) r
--     where f s (k, v) = S.replace ("@" ++ k ++ "@") v s
